package com.hebada.service;

import com.hebada.converter.ProductConverter;
import com.hebada.domain.Product;
import com.hebada.repository.ProductJpaRepository;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.Collections;
import java.util.List;

/**
 * Created by paddy on 2017/9/10.
 */
@Service
public class ProductService {

    @Inject
    private ProductJpaRepository productJpaRepository;
    @Inject
    private ProductConverter productConverter;

    public Product get(long id) {
        return productJpaRepository.findOne(id);
    }

    @Transactional
    public void save(Product product) {
        productJpaRepository.save(product);
    }

    @Transactional
    public void update(long id, Product product) {
        Product productDomain = productJpaRepository.findOne(id);
        if (productDomain == null) return;
        productJpaRepository.save(productConverter.convertToProduct(product, productDomain));
    }

    @Transactional
    public void delete(long id) {
        productJpaRepository.delete(id);
    }

    public Page<Product> findAllByCatalogId(long catalogId, int currentPage, int pageSize) {
        return productJpaRepository.findAllByCatalogId(catalogId, new PageRequest(currentPage, pageSize));
    }

    public List<Product> findAllByProductIds(List productIds) {
        if (CollectionUtils.isEmpty(productIds)) return Collections.emptyList();
        return productJpaRepository.findAll(productIds);
    }

    public List<Product> findProductListByName(String name) {
        if (StringUtils.isEmpty(name)) return Collections.EMPTY_LIST;
        return productJpaRepository.findAll(where(name));
    }

    private Specification where(final String name) {
        return new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                predicate.getExpressions().add(cb.like(root.get("name"), "%" + name + "%"));
                return predicate;
            }
        };
    }
}
